<template>
  <d2-container>
    <template slot="header">
			<el-form class="header-area" ref="indexForm" :model="indexForm" label-width="80px" style="height: auto">
				<el-row>
					<el-col :span="5">
						<el-form-item label="餐品名称" prop="productName">
              <el-input v-model="indexForm.productName" placeholder="请输入餐品名称" clearable style="width: 100%;"></el-input>
            </el-form-item>
					</el-col>
          <el-col :span="5">
						<el-form-item label="分类" prop="categoryId">
              <el-select v-model="indexForm.categoryId" placeholder="请选择分类" style="width: 100%;">
								<el-option v-for=" (item,key) of categoryList" :key="key" :value="item.id" :label="item.categoryName"></el-option>
						</el-select>
            </el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="售卖状态" prop="saleStatus">
							<el-select v-model="indexForm.saleStatus" placeholder="请选择售卖状态" style="width: 100%;">
								<el-option value="-1" label="请选择">请选择</el-option>
								<el-option value="1" label="在售">在售</el-option>
								<el-option value="0" label="停售">停售</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<div class="search-submit">
							<el-button type="primary" size="medium" loading v-if="loading">查询</el-button>
							<el-button type="primary" size="medium" @click="submitForm" v-else>查询</el-button>
							<el-button type="primary" plain size="medium" @click="resetForm('indexForm')">重置</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</template>

   <template>
    <el-button slot="header" type="primary" style="margin-bottom: 5px">新 增</el-button>
      <el-table
          :data="tableData"
          stripe border 
          :span-method="objectSpanMethod"
          row-key="id"
          style="width: 100%;">
          <el-table-column label="排序号" prop="sort" align="center" width="70"></el-table-column>
          <el-table-column label="餐品编号" prop="productCode" align="center" width="130"></el-table-column>
          <el-table-column label="餐品名称" prop="productName" align="center" width="160"></el-table-column>
          <el-table-column label="规格" prop="originalPropertyValueNames" align="center"></el-table-column>
          <el-table-column label="售价(元)" prop="price" align="center" width="100"></el-table-column>
          <el-table-column label="会员价(元)" prop="memberPrice" align="center" width="100"></el-table-column>
          <el-table-column label="返现金额(元)" prop="cashBackAmount" align="center" width="120"></el-table-column>
          <el-table-column label="分类" prop="categoryName" align="center" width="100"></el-table-column>
          <el-table-column label="图片" prop="mainImage" align="center" width="80">
            <template slot-scope="scope">
						<el-image :src="imgUrlHeader + scope.row.mainImage" style="width: 50px; height: 50px;"></el-image>
					</template>
          </el-table-column>
          <el-table-column label="售卖状态" prop="saleStatus" align="center" width="80">
            <template slot-scope="scope">
						<template v-if="scope.row.saleStatus == 1">
							在售
						</template>
						<template v-if="scope.row.saleStatus == 0">
							停售
						</template>
					</template>
          </el-table-column>
          <el-table-column label="类型" prop="categoryType" align="center" width="80">
            <template slot-scope="scope">
						<template v-if="scope.row.categoryType == 1">单品</template>
						<template v-if="scope.row.categoryType == 2">加菜</template>
            <template v-if="scope.row.categoryType == 3">饮料/自选/餐盒/补差</template>
					</template>
          </el-table-column>
          <el-table-column label="子类型" prop="categoryTypeSub" align="center" width="80">
            <template slot-scope="scope">
						<template v-if="scope.row.categoryTypeSub == 0">-</template>
						<template v-if="scope.row.categoryTypeSub == 1">打包盒</template>
            <template v-if="scope.row.categoryTypeSub == 2">费用</template>
            <template v-if="scope.row.categoryTypeSub == 3">荤菜</template>
            <template v-if="scope.row.categoryTypeSub == 4">素菜</template>
					</template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" align="center" :formatter="forDate" width="100"></el-table-column>
          <el-table-column label="修改时间" prop="reviseTime" align="center" :formatter="forDate" width="100"></el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="160">
					  <template slot-scope="scope">
						  <el-button type="primary" size="small" @click="viewDetails(scope.row.productId)">查看</el-button>
              <el-button type="warning" plain size="small">编辑</el-button>
              <el-button type="success" v-if="scope.row.saleStatus==0" plain size="small" @click.native.prevent="operateSaleStatusOn(scope.$index, scope.row)">启售</el-button>
              <el-button type="success" v-if="scope.row.saleStatus==1" plain size="small" @click.native.prevent="operateSaleStatusStop(scope.$index, scope.row)">停售</el-button>
              <el-button type="danger" plain size="small" @click.native.prevent="deleteRow(scope.row)">删除</el-button>
					  </template>
				  </el-table-column>
        </el-table> 
    </template>

    <template slot="footer">
			<div class="page">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</template>
  </d2-container>
</template>

<script>
import { findSingleProductListByPage, onSaleProduct, stopSaleProduct, del } from '@api/restaurant/merchant/singleProduct'
import { findAllFirstList} from '@api/restaurant/merchant/productCategory'
import dayjs from 'dayjs'
import { ossDomain } from '@api/sys.common'
export default {
  name: 'singleProduct-index',
  data () {
    return {
      indexForm: {
        productName: '',
        categoryId: '',
        saleStatus: '-1'
      },
      categoryList: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,

      loading: false,
      imgUrlHeader: '' // 图片地址
    }
  },
  mounted () {
    this.fetchData()
    this.getAllFirstList()
    this.imgUrlHeader = ossDomain
  },
  methods: {
    fetchData () {
      findSingleProductListByPage({
        productName: this.indexForm.productName,
        categoryId: this.indexForm.categoryId,
        saleStatus: this.indexForm.saleStatus === '-1' ? '' : this.indexForm.saleStatus,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
	    .then(res => {
		  this.tableData = res.data.content
      this.getSpanArr(this.tableData)
		  this.total = res.data.total
		  this.loading = false
	    })
    },
    forDate (row, column) {
	    var formatTime = ''
	    if (column.property == 'createTime') {
	      formatTime = row.createTime == null ? '' : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
	    }
	    if (column.property == 'reviseTime') {
	      formatTime = row.reviseTime == null ? '' : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss')
	    }
	    return formatTime
    },
    resetPage () {
	    this.currentPage = 1
	    this.pageSize = 10
	    this.total = 0
	    this.fetchData()
    },
    handleSizeChange (val) {
	    this.pageSize = val
	    this.fetchData()
    },
    handleCurrentChange (val) {
	    this.currentPage = val
	    this.fetchData()
    },
    submitForm (formName) {
      if (this.loading) {
		  return
      }
      this.loading = true
      this.resetPage()
    },
    resetForm (formName) {
	    this.$refs[formName].resetFields()
	    this.resetPage()
    },
    getAllFirstList () {
      this.loading = true
      findAllFirstList({

      }).then(res => {

        res.data.forEach(item=>{
          if(item.categoryType != 4){
            this.categoryList.push(item)
          }
        })

        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    },
    // 获取合并的数据
    getSpanArr (data) {
      this.spanArr = [] // 合并单元格标识数组
      // data就是我们从后台拿到的数据
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].productId === data[i - 1].productId) {
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.pos = i
          }
        }
      }
    },
    // 合并单元格
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex != 3 && columnIndex != 4 && columnIndex != 5 && columnIndex != 6) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // 启售
    operateSaleStatusOn(index,row) {
      this.$confirm("确认启售【"+ row.productName + "】？").then(_ => {
        this.loading = true
        onSaleProduct({
          id: row.productId
        }).then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: "success" });
			  this.fetchData();
              this.loading = false
            } else {
              this.$message({message: res.message, type:'error'});
              return;
            }
          }).catch(err => {
            console.log("err", err);
            this.loading = false;
          });
      });
    },
    // 停售
    operateSaleStatusStop(index,row) {
      this.$confirm("确认停售【"+ row.productName + "】？").then(_ => {
        this.loading = true
        stopSaleProduct({
          id: row.productId
        }).then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: "success" });
			        this.fetchData();
              this.loading = false
            } else {
              this.$message({message: res.message, type:'error'});
              return;
            }
          }).catch(err => {
            console.log("err", err);
            this.loading = false;
          });
      });
    },
    deleteRow(row) {
      this.$confirm("确认删除" + row.productName + "？").then(_ => {
        this.loading = true
        del({
          id:row.productId
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: "success" });
              this.fetchData();
              this.loading = false
            } else {
              this.$message({message: res.message, type:'error'});
              return;
            }
          })
          .catch(err => {
            console.log("err", err);
            this.loading = false;
          });
      });
    },
  }
}
</script>
